package com.ajocer.springbootinit.config;

import io.milvus.client.MilvusServiceClient;
import io.milvus.param.ConnectParam;
import io.milvus.param.IndexType;
import io.milvus.param.MetricType;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

/**
 * Milvus向量数据库配置
 */
@Configuration
@Data
@Slf4j
public class MilvusConfig {

    @Value("${milvus.host}")
    private String host;

    @Value("${milvus.port}")
    private int port;

    @Value("${milvus.collection}")
    private String collection;

    @Value("${milvus.dimension}")
    private int dimension;

    @Value("${milvus.index-type}")
    private String indexType;

    @Value("${milvus.metric-type}")
    private String metricType;
    
    private MilvusServiceClient milvusServiceClient;

    /**
     * 创建Milvus客户端
     * 使用单例模式确保只创建一个客户端实例
     */
    @Bean
    public MilvusServiceClient milvusClient() {
        if (milvusServiceClient == null) {
            log.info("创建Milvus客户端连接: {}:{}", host, port);
        ConnectParam connectParam = ConnectParam.newBuilder()
                .withHost(host)
                .withPort(port)
                .build();
            milvusServiceClient = new MilvusServiceClient(connectParam);
        }
        return milvusServiceClient;
    }

    /**
     * 获取索引类型
     */
    public IndexType getIndexType() {
        return IndexType.valueOf(indexType);
    }

    /**
     * 获取度量类型
     */
    public MetricType getMetricType() {
        return MetricType.valueOf(metricType);
    }
    
    /**
     * 关闭Milvus客户端连接
     */
    @PreDestroy
    public void close() {
        if (milvusServiceClient != null) {
            log.info("关闭Milvus客户端连接");
            milvusServiceClient.close();
            milvusServiceClient = null;
        }
    }
} 